<?php

class Autoloader
{
    /**
     * namespace psr4
     * @var array
     */
    public static $psr4 = array();

    /**
     * namespace alias
     * @var array
     */
    public static $alias = array();

    /**
     * root path
     * @var string
     */
    public static $directory;

    public static $paths = array();

    /**
     * autoload functin
     * @param  string $class namespace
     * @return [type]        [description]
     * @author marvin
     * @date   2016-03-21
     */
    public static function load($class)
    {
        $namespace = str_replace(array('\\', '\\'), DS, ltrim($class, '\\'));
        $name_arr = explode(DS, $namespace);
        $reset = reset($name_arr);
        if (isset(self::$psr4[$reset])) {
            $name_arr[0] = self::$psr4[$reset];
            $namespace = implode(DS, $name_arr);
        }
        $lower = strtolower($namespace);

        foreach (self::$paths as $path) {
            $rel_namspace = $path . $namespace;
            if (is_file($rel_namspace . '.php')) {
                if (array_key_exists($rel_namspace, self::$alias)) {
                    return class_alias(self::$alias[$namespace], $rel_namspace);
                }

                if (is_file(self::$directory . $rel_namspace . '.php')) {
                    return require self::$directory . $rel_namspace . '.php';
                }
            }
        }

        return false;
    }

    public static function psr4($key, $value)
    {
        self::$psr4[$key] = $value;
    }
}